<?php

namespace App\Service\Auth;

use App\Constants\Chat\RedisKey;
use App\Constants\StatusCode;
use App\Foundation\Traits\Singleton;
use App\Model\Chat\ChatGroup;
use App\Pool\Redis;
use App\Service\BaseService;
use App\Model\Auth\User;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\Utils\ApplicationContext;
use Hyperf\Utils\Context;
use App\Foundation\Utils\JWT;

/**
 * 用户服务基础类
 * Class UserService
 * @package App\Service\Auth
 * @Author YiYuan-Lin
 * @Date: 2020/10/29
 */
class UserService extends BaseService
{
    use Singleton;

    /**
     * @Inject()
     * @var JWT
     */
    private $jwt;

    /**
     * 根据Token获取用户的信息
     * @param null $token
     * @return User
     */
    public function getUserInfoByToken($token = null): User
    {
        if ($userInfo = context_get('user_info')) {
            return $userInfo;
        }
        //获取Token解析的数据
        $token = $token ?: JWT::handleToken($this->request->getHeaderLine('authorization'));
        $parserData = $this->jwt->getParserData($token);
        return User::getOneByUid($parserData['uid']);
    }

    public function getByUid($user_id)
    {
        $redis = Redis::getInstance();
        $key = RedisKey::USER_KEY . ':' . $user_id;
        $redis->del($key);
        $cache = $redis->get($key);
        if ($cache) {
            return unserialize($cache);
        }
        $user = User::query()->select('*')->where([
            'id' => $user_id
        ])->first()->toArray();
        $redis->set($key, serialize($user), RedisKey::USER_CACHE_TTL);
        return $user;
    }


}
